package com.shigu.agent.processes;

import com.opentae.data.mall.beans.MoProv;
import com.opentae.data.mall.beans.MoUserNormalProv;
import com.opentae.data.mall.examples.ManagerUserRoleExample;
import com.opentae.data.mall.examples.MoUserNormalProvExample;
import com.opentae.data.mall.interfaces.*;
import com.shigu.agent.bo.UserBO;
import com.shigu.agent.enums.UserRoleType;
import com.shigu.agent.exceptions.YeepayException;
import com.shigu.agent.model.MoAgent;
import com.shigu.agent.model.MoBusiness;
import com.shigu.agent.model.impl.MoBusinessImpl;
import com.shigu.main4.tools.SpringBeanFactory;
import com.shigu.passageway.exceptions.PassagewayException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class BusinessProcessImpl implements BusinessProcess{

    private static final Logger logger = LoggerFactory.getLogger(BusinessProcessImpl.class);

    @Autowired
    private ManagerUserRoleMapper managerUserRoleMapper;

    @Autowired
    private MoUserNormalProvMapper moUserNormalProvMapper;

    @Autowired
    private MoProvMapper moProvMapper;

    @Value("${me.operator_id}")
    private Long defaultAgentId;
    /**
     * 创建一个商户
     * @param telephone
     * @param password
     * @param fromId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createBusinessman(String oemTag,String telephone, String password, Long fromId) {
        UserBO bo=new UserBO();
        bo.setNick(telephone);
        bo.setPassword(password);
        bo.setUserName(telephone);
        bo.setOemTag(oemTag);
        List<Long> roleIds=new ArrayList<>();
        roleIds.add(UserRoleType.BUSINESS.getRoleId());
        bo.setRoleIds(roleIds);
        MoBusiness business= SpringBeanFactory.getBean(MoBusiness.class,bo);
        if (fromId == null) {
            fromId=defaultAgentId;
        }else{//检查是否代理
            ManagerUserRoleExample roleExample=new ManagerUserRoleExample();
            roleExample.createCriteria().andUserIdEqualTo(fromId).andRoleIdEqualTo(UserRoleType.AGENT.getRoleId());
            if (managerUserRoleMapper.countByExample(roleExample)==0) {
                //加入推荐信息
                MoBusiness frombusiness= SpringBeanFactory.getBean(MoBusiness.class,fromId);
                frombusiness.spreadByMe(business.getUserId());
                fromId=defaultAgentId;//这种用户归默认代理所有
            }
        }
        MoAgent agent=SpringBeanFactory.getBean(MoAgent.class,fromId);
        agent.joinBusiness(business.getUserId());
        return business.getUserId();
    }

    /**
     * 记录用户使用过的省份，最多5个，如果超过，删除最早一个，如果有，把当前一个提到最先
     * @param userId 用户ID
     * @param provId 省ID
     */
    @Override
    public void useProvRecord(Long userId, Long provId) {
        MoUserNormalProvExample example=new MoUserNormalProvExample();
        example.createCriteria().andUserIdEqualTo(userId);
        example.setOrderByClause("use_time desc");
        List<MoUserNormalProv> normals=moUserNormalProvMapper.selectByExample(example);
        for (MoUserNormalProv p:normals){
            if(p.getProvId().equals(provId)){
                p.setUseTime(new Date());
                moUserNormalProvMapper.updateByPrimaryKeySelective(p);
                return;
            }
        }

        if (normals.size()>=5) {
            moUserNormalProvMapper.deleteByPrimaryKey(normals.get(normals.size()-1).getNormalId());;
        }
        MoUserNormalProv mu=new MoUserNormalProv();
        mu.setUseTime(new Date());
        mu.setProvId(provId);
        mu.setUserId(userId);
        MoProv prov=moProvMapper.selectByPrimaryKey(provId);
        mu.setProvName(prov.getProvName());
        moUserNormalProvMapper.insertSelective(mu);
    }

    @Override
    public int realCheck(Long userId,String idCard, String realName, String cashCard, String bank, String location, Long areaId,String telephone) throws PassagewayException {
        MoBusiness business= SpringBeanFactory.getBean(MoBusiness.class,userId);
            business.realCheck(idCard,realName,cashCard,bank,location,areaId,telephone);
            return 1;

    }

    @Override
    public int modifyRealCheck(Long userId, String idCard, String realName, String cashCard, String bank, String location, Long areaId, String telephone) throws PassagewayException {
        MoBusiness business= SpringBeanFactory.getBean(MoBusiness.class,userId);
        business.updateCheck(idCard,realName,cashCard,bank,location,areaId,telephone);
        return 0;
    }
}
